package routers

import (
	"github.com/gin-gonic/gin"
	"goadmin/controllers/web"
	"goadmin/utils"
	"log"
	"net/http"
)

// 提供测试页面
func serveHome(c *gin.Context) {
	c.Header("Content-Type", "text/html; charset=utf-8")
	html := `
	<!DOCTYPE html>
	<html>
	<head>
		<title>Gin WebSocket测试</title>
	</head>
	<body>
		<h1>WebSocket测试</h1>
		<form id="form" onsubmit="sendMessage(); return false;">
			<input id="input" type="text" placeholder="输入消息...">
			<button type="submit">发送</button>
		</form>
		<pre id="log"></pre>

		<script>
			const ws = new WebSocket('ws://' + window.location.host + '/ws?client_id=1000');
			//const ws = new WebSocket('wss://go.liqinglin.cn/ws?client_id=1000');
			function log(message) {
				const logElement = document.getElementById('log');
				logElement.textContent += message + '\n';
				logElement.scrollTop = logElement.scrollHeight;
			}
			
			ws.onopen = function() { log('连接已建立'); };
			ws.onmessage = function(event) { log('收到: ' + event.data); };
			ws.onclose = function() { 
				log('连接已关闭');
				setTimeout(() => window.location.reload(), 3000);
			};
			ws.onerror = function(error) { log('错误: ' + error); };
			
			function sendMessage() {
				const input = document.getElementById('input');
				const message = input.value.trim();
				if (message) {
					ws.send(message);
					log('发送: ' + message);
					input.value = '';
				}
			}
		</script>
	</body>
	</html>
	`
	c.String(http.StatusOK, html)
}
func sendMessage(c *gin.Context) {
	wsManager := utils.GetWebSocketManager()
	log.Println("发送消息")
	result := wsManager.SendToClient("1000", []byte("当前时间是："+utils.GetDate()))
	log.Println("发送消息结果%b", result)
}
func DefaultRoutersInit(r *gin.Engine) {
	defaultRouters := r.Group("/")
	{
		defaultRouters.GET("/", web.DefaultController{}.Index)
		defaultRouters.GET("/news", web.DefaultController{}.News)
		defaultRouters.GET("/ws_test", web.DefaultController{}.WsTest)
		defaultRouters.GET("/send_message", sendMessage)
	}
}
